from goods.models import GoodsChannel


def get_categories():
    categories = {}  # 用来包装所有商品类别数据
    goods_channels_qs = GoodsChannel.objects.order_by('group_id', 'sequence')
    for channel in goods_channels_qs:
        group_id = channel.group_id

        # 判断当前的组号在字典中是否存在
        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        cat1 = channel.category  # 获取一级类别数据
        cat1.url = channel.url  # 将频道中的url绑定给一级类型对象

        categories[group_id]['channels'].append(cat1)

        cat2_qs = cat1.subs.all()
        for cat2 in cat2_qs:
            cat2.sub_cats = cat2.subs.all()
            categories[group_id]['sub_cats'].append(cat2)

    return categories